# -*- coding: utf-8 -*-
'''
#----------------------------------------------------------------------------------------
# 功能：更新所有差异数据到内网服务器
# 用法：python send_update_client.py -p "E:/Seven/ElementUnityWin/Z3DExport/Win" -b "E:/Seven/ElementUnityWin/Z3DExport_backup/Win" -d "E:/Seven/ElementUnityWin/Z3DExport_diff/Win"
#----------------------------------------------------------------------------------------
'''

import argparse
import os,sys
from flib.utils import *

if getenv("SEVEN_WORKSPACE",None):
    tool_path = getenv("SEVEN_WORKSPACE") + "/trunk" + "/PC/ElementUnityWin/Tools"
else:
    tool_path = "F:/Seven/ElementUnityWin/Tools"
BComp = '''F:/Program Files (x86)/Beyond Compare 4/BComp.com'''
bcDiffInner = '''option stop-on-error
option confirm:yes-to-all
load "%1" "%2"
expand all
filter "-*.bat;-*.exe;-*.db;-*.svn;-.svn\\"
criteria binary
select left.diff left.orphan
copyto all path:base "%3"'''

bcBackUpInner='''option stop-on-error
option confirm:yes-to-all
load "%1" "%2"
expand all
filter "-.svn\"
select left right
sync create-empty mirror:left->right
'''

def usage():
    ZLPrint(__doc__)

#BC打包差异资源
def diff_compare(args):
    try:
        backup_dir = args.backup_dir or args.asset_dir + "_backup"
        diff_dir = args.diff_dir or args.asset_dir + "_diff"
        ZLPrint ("清理上次更新资源:", diff_dir)
        exec_sh(cmds='''rm -rf "{diff_dir}"'''.format(diff_dir=diff_dir))
        ZLPrint ('''BC选出差异资源:
                newAssets:{}
                oldAssets:{}
                diffAssets:{}'''.format(args.asset_dir, backup_dir, diff_dir))
        if not os.path.exists(backup_dir):
            os.makedirs(backup_dir)
        safe_execute(cmds='''"{}" @"{}" "{}" "{}" "{}"'''.format(
            args.bc_com,
            os.path.join(os.getcwd(), "bcDiffInner.txt"),
            args.asset_dir,
            backup_dir,
            diff_dir))
        ZLPrint("BC结束，差异文件保存在目录：", diff_dir)
        return True
    except Exception as e:
        ZLPrint ("[error]", "BC失败，失败原因：",str(e))
        raise e
def backup_dir(args):
    try:
        ZLPrint("备份资源")
        backup_dir = args.backup_dir or args.asset_dir + "_backup"
        if not os.path.exists(backup_dir):
            os.makedirs(backup_dir)
        safe_execute(cmds='''"{}" @"{}" "{}" "{}"'''.format(
            args.bc_com,
            os.path.join(os.getcwd(), "bcBackUpInner.txt"),
            args.asset_dir,
            backup_dir))
        ZLPrint("BC结束，备份保存在目录：", backup_dir)
        return True
    except Exception as e:
        ZLPrint ("[error]", "BC失败，失败原因：",str(e))
        raise e

def send_update(args):
    try:
        ZLPrint("上传更新资源")
        diff_dir = args.diff_dir or args.asset_dir + "_diff"
        if not os.path.exists(diff_dir):
            ZLPrint("没有文件发生变化，资源更新完成")
            return
        safe_execute(
            cmds='''sh {tools_path}/make-client/resource-update.sh "../elementpacktool/ElementPackTool-pc.exe" {update_url} "{local_dir}"'''.format(
                tools_path=tool_path,
                update_url="http://10.236.100.38/seven_xevs/pc",
                local_dir=diff_dir.replace('\\', '/')), logout=True)
    except Exception as e:
        raise e
    finally:
        diff_dir = args.diff_dir or args.asset_dir + "_diff"
        exec_sh(cmds='''rm -rf "{diff_dir}"'''.format(diff_dir=diff_dir))

def main():
    parser = argparse.ArgumentParser(prog='send_update_client.py', usage=__doc__)
    parser.add_argument("--asset_dir", "-p", help="资源所在路径", type=str,default="F:/Seven/Z3DExport/Win")
    parser.add_argument("--backup_dir", "-b", help="备份资源所在路径", type=str)
    parser.add_argument("--diff_dir", "-d", help="增量资源所在路径", type=str)
    parser.add_argument("--bc-com", help="BeyondCompare路径", type=str, default=BComp)
    args = parser.parse_args()
    #检查
    if not args.asset_dir: usage(), sys.exit(1)
    bcCallFile = os.path.join(os.getcwd(), "bcDiffInner.txt")
    if not os.path.exists(bcCallFile):
        with open(bcCallFile, "w") as f:
            f.write(bcDiffInner)
            f.close()
    bcCallFile = os.path.join(os.getcwd(), "bcBackUpInner.txt")
    if not os.path.exists(bcCallFile):
        with open(bcCallFile, "w") as f:
            f.write(bcBackUpInner)
            f.close()
    diff_compare(args)
    send_update(args)
    backup_dir(args)
    sys.exit(0)

if __name__ == '__main__':
    main()